3.4 获取查询参数
在HTTP协议中,查询参数(Query Parameters)是在URL中用于向服务器传递数据的一种方式。查询参数通常用于GET请求, 并将数据附加在URL的尾部,按照键值对的形式表示。查询参数以问号(?)开始,然后是一个或多个键值对,每个键值对之间有&符号分隔
以下是一个示例URL,其中包含查询参数:
http://127.0.0.1:8000/app03/test?name=liuxu&age=18
在Django获取查询参数方式有两种(request.get_full_path()、request.GET)。这两种方式都可以获取查询参数, 但是第一个需要我们手动解析数据,一般我们使用第二种方式获取查询参数。
Views:
def test3(request):
print ("1")
print (request.get_full_path)
return HttpResponse( "显示查询参数" )
URL
urlpatterns = [
path( "test" ,views.test),
#一旦调用test1, 那么kwargs将会以关键字的a=100,b=200这样的形式传给test1
path( "test1" , views.test1,kwargs={ "a" : 100 , "b" : 200 }),
#test2(request,year,month)
path( "test2/ <year>/<month>" , views.test2),
path( "test3" , views.test3),
]
地址中输入:
127.0.0.1:8000/app03/test3?wd="汽车"
返回值:
1
<bound method HttpRequest.get_full_path of <WSGIRequest: GET '/app03/test3?wd=%22%E6%B1%BD%E8%BD%A6%22'>>
[06/May/2024 22:17:00] "GET /app03/test3?wd=%22%E6%B1%BD%E8%BD%A6%22 HTTP/1.1" 200 18
地址中输入为英文:
127.0.0.1:8000/app03/test3?wd="car"
返回值:
1
<bound method HttpRequest.get_full_path of <WSGIRequest: GET '/app03/test3?wd=%22car%22'>>
[06/May/2024 22:20:19] "GET /app03/test3?wd=%22car%22 HTTP/1.1" 200 18
127.0.0.1:8000/app03/test3?wd=car
def test3(request):
print ("1")
print (request.get_full_path)
print (request.GET)
return HttpResponse( "显示查询参数" )
返回:
1
<bound method HttpRequest.get_full_path of <WSGIRequest: GET '/app03/test3?wd=car'>>
< QueryDict: {'wd': ['car']}>
[06/May/2024 22:25:21] "GET /app03/test3?wd=car HTTP/1.1" 200 18
输入改为汽车:
127.0.0.1:8000/app03/test3?wd=汽车
1
<bound method HttpRequest.get_full_path of <WSGIRequest: GET '/app03/test3?wd=%E6%B1%BD%E8%BD%A6'>>
<QueryDict: {'wd': ['汽车']}>
[06/May/2024 22:26:05] "GET /app03/test3?wd=%E6%B1%BD%E8%BD%A6 HTTP/1.1" 200 18
改成字典取值:
def test3(request):
print ("1")
print (request.get_full_path)
print (request.GET["wd"])
return HttpResponse( "显示查询参数" )
返回:
1
<bound method HttpRequest.get_full_path of <WSGIRequest: GET '/app03/test3?wd=%E6%B1%BD%E8%BD%A6'>>
汽车
[06/May/2024 22:29:42] "GET /app03/test3?wd=%E6%B1%BD%E8%BD%A6 HTTP/1.1" 200 18
属性/方法 | 描述 |
---|---|
request.GET | 包括所有的GET请求参数,以字典形式返回 |
request.GET.get(key,default=Non) | 获取指定键的对应值,如果键不存在则返回默认值 |
request.GET.getlist(key) | 获取指字键的所有值,返回一个列表 |
request.GET.keys() | 返回包含所有参数键的列表 |
request.GET.values() | 返回包含所有参数值的表表 |
request.GET.items() | 返回包含所有参数键值对的列表 |
request.GET.urlencode() | 将GET请求参数编码为URL查询字符串的形式 |
request.GET._contains_(key) | 检查指字健是否存在于GET请求参数中,返回布尔值 |